package com.hyf.msmservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.hyf.msmservice.service.MsmService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class MsmServiceimpl implements MsmService {

    // 发送短信的方法
    @Override
    public boolean send(Map<String, Object> param, String phone) {


        if(StringUtils.isEmpty(phone)) return false;

        DefaultProfile profile =
              DefaultProfile.getProfile("default", "LTAI4GBABS7Sq8MLf2RNwLuu", "ynfsD31FLdcRoQVFSIdHP7AeoKaf4o");// 第一个是地狱借点 第二个是id 第三个是密钥  也是用的别人的
        IAcsClient client = new DefaultAcsClient(profile);


        // 设置相关参数
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");


        // 设置发送相关的参数
        request.putQueryParameter("PhoneNumbers", phone);// 发送的手机号
        request.putQueryParameter("SignName", "阿昌日语在线教育网站");// 申请阿里云签名的名称  用的别人的
        request.putQueryParameter("TemplateCode", "SMS_212711286");//申请阿里云模板 code
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));// 验证码
/* 课件中的写法
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }*/

        // 最终发送
        try {
            CommonResponse response = client.getCommonResponse(request);

            boolean success = response.getHttpResponse().isSuccess();

            return  success;
        }catch (Exception e) {
             e.printStackTrace();
            return false;
        }


    }
}
